package com.tanhua.dubbo.api;

import com.sun.xml.internal.rngom.ast.builder.CommentList;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author anshuai
 * @create 2021-02-05 16:34
 */
@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询用户喜欢了多少人
     * @param userId 用户id
     * @return
     */
    @Override
    public long queryLikeCount(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 查询用户有多少粉丝（有多少人喜欢这个用户）
     * @param userId 用户id
     * @return
     */
    @Override
    public long queryFansCount(long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 查询好友数量（相互喜欢）
     * @param userId 用户id
     * @return
     */
    @Override
    public long queryFriendsCount(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, Friend.class);
    }

    /**
     * 分页查询好友列表（相互喜欢列表）
     * @param userId 用户id
     * @param page 页码
     * @param pagesize 查询几条
     * @return
     */
    @Override
    public PageResult<CommonLikeUser> queryFriendsList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        ArrayList<CommonLikeUser> commonLikeUsers = new ArrayList<>();
        for (Friend friend : friendList) {
            CommonLikeUser likeUser = new CommonLikeUser();
            likeUser.setTargetUserId(friend.getFriendId());
            likeUser.setScore(queryScore(userId,likeUser.getTargetUserId()));

            commonLikeUsers.add(likeUser);
        }

        int pages = (int) Math.ceil(count*1.0/pagesize);

        return new PageResult<>((int)count,pagesize,pages,page,commonLikeUsers);
    }

    /**
     * 分页查询喜欢的用户列表
     * @param userId 用户id
     * @param page 页码
     * @param pagesize 查询几条
     * @return
     */
    @Override
    public PageResult<CommonLikeUser> queryLikeList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        ArrayList<CommonLikeUser> commonUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(userLike.getLikeUserId());
            user.setScore(queryScore(userId,user.getTargetUserId()));

            commonUserList.add(user);
        }

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count,pagesize,pages,page,commonUserList);
    }

    /**
     * 分页查询粉丝列表
     * @param userId 用户id
     * @param page 页码
     * @param pagesize 查询几条
     * @return
     */
    @Override
    public PageResult<CommonLikeUser> queryFansList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);
        List<CommonLikeUser> commonLikeUserList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {

            CommonLikeUser user = new CommonLikeUser();

            user.setTargetUserId(userLike.getUserId());
            user.setScore(queryScore(userId,user.getTargetUserId()));

            commonLikeUserList.add(user);
        }

        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int)count,pagesize,pages,page,commonLikeUserList);
    }

    /**
     * 分页查询来访者
     * @param userId 用户id（被访问者）
     * @param page 页码
     * @param pagesize 查询几条
     * @return
     */
    @Override
    public PageResult<CommonLikeUser> findVisitorList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .with(PageRequest.of(page-1, pagesize));

        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
        long count = mongoTemplate.count(query, Visitor.class);

        List<CommonLikeUser> commonUserList = new ArrayList<>();
        for (Visitor visitor : visitorList) {
            CommonLikeUser user = new CommonLikeUser();

            user.setTargetUserId(visitor.getVisitorUserId());
            user.setScore(queryScore(userId,user.getTargetUserId()));

            commonUserList.add(user);
        }

        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int)count,pagesize,pages,page,commonUserList);
    }

    /**
     * 删除某一用户对当前用户的喜欢
     * @param userId 用户id
     * @param likeUserId 将要取消喜欢的用户id
     */
    @Override
    public void delete(Long userId, Long likeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        mongoTemplate.remove(query,UserLike.class);
    }

    /**
     * 保存喜欢
     * @param userId 当前用户id
     * @param likeUserId 喜欢的用户id
     */
    @Override
    public String saveUserLike(Long userId, Long likeUserId) {
        // 判断喜欢关系是否存在
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));

        if (mongoTemplate.count(query, UserLike.class) > 0) {
            return null;
        }

        UserLike userLike = new UserLike();
        userLike.setId(ObjectId.get());
        userLike.setLikeUserId(likeUserId);
        userLike.setUserId(userId);
        userLike.setCreated(System.currentTimeMillis());

        mongoTemplate.save(userLike);
        return userLike.getId().toHexString();
    }

    /**
     * 是否相互喜欢
     * @param userId 当前用户id
     * @param likeUserId 喜欢的用户id
     * @return
     */
    @Override
    public Boolean isMutualLike(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);

        Criteria criteria = new Criteria().orOperator(criteria1, criteria2);
        return mongoTemplate.count(Query.query(criteria), UserLike.class) == 2;
    }

    /**
     * 查询两个用户之间的缘分值
     * @param userId 用户id
     * @param targetUserId 目标用户id
     * @return 缘分值得分
     */
    private Double queryScore(Long userId,Long targetUserId){
        Query query = new Query(Criteria.where("toUserId").is(userId).and("userId").is(targetUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null){
            return 95D;
        }

        return recommendUser.getScore();
    }
}
